package org.example.service.impl;

import org.example.dao.IUserDao;
import org.example.entity.UserEntity;
import org.example.exception.UserException;
import org.example.service.IUserService;
import org.example.util.Md5Util;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author HanJiafeng
 */
@Service
public class UserServiceImpl implements IUserService {
    private final IUserDao userDao;

    public UserServiceImpl(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public Boolean checkUsername(String username) throws UserException {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        try {
            int count = userDao.selectSelective(userEntity).size();
            return count > 0;
        } catch (IOException e) {
            throw new UserException("服务器内部异常，请联系管理员", e);
        }
    }

    @Override
    public int regist(UserEntity userEntity) throws UserException {
        String newPassword = Md5Util.getMd5Encoding(userEntity.getPassword());
        userEntity.setPassword(newPassword);
        try {
            return userDao.insertSelective(userEntity);
        } catch (IOException e) {
            throw new UserException("注册失败", e);
        }
    }

    @Override
    public UserEntity login(String username, String password) throws UserException {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        List<UserEntity> userEntityList;
        try {
            userEntityList = userDao.selectSelective(userEntity);
        } catch (IOException e) {
            throw new UserException("服务器内部错误，请联系管理员", e);
        }
        if (userEntityList.size() == 0) {
            throw new UserException("用户名不存在");
        } else if (userEntityList.size() != 1) {
            throw new UserException("服务器内部错误，请联系管理员");
        }
        userEntity = userEntityList.get(0);
        if (!Md5Util.getMd5Encoding(password).equals(userEntity.getPassword())) {
            throw new UserException("密码错误");
        }
        return userEntity;
    }
}
